//
//  SGFAddYSViewController.m
//  Estate
//
//  Created by wangdongdong on 16/7/12.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "SGFAddYSViewController.h"
#import "DefaineCell.h"
#import "selectBtnCell.h"
#import "PositionTableCell.h"
#import "B_wuLiaoCell.h"
#import "QianDTableCell.h"
#import "OrientationViewController.h"
#import "ChooseMaterialCell.h"
#import "H1_ImagesCell.h"
#import "UIActionSheet+Common.h"
#import "PictureViewController.h"


#import "ProjectUserModel.h"
#import "PositionBlockModel.h"

@interface SGFAddYSViewController ()

@property (strong, nonatomic) Tweet *curTweet;  /** 附件模型*/
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;

// 位置
@property (strong, nonatomic) PositionTableCell *positionCell;
// 标题cell
@property (strong, nonatomic) QianDTableCell *titleCell;
// 内容cell
@property (strong, nonatomic) B_wuLiaoCell *contentCell;

// 创建时间
@property (copy, nonatomic) NSString *nowTime;
// 创建标题
@property (copy, nonatomic) NSString *titleStr;
// 内容
@property (copy, nonatomic) NSString *content;

// 隐蔽
@property (copy, nonatomic) NSString *ybButton;
// 检验
@property (copy, nonatomic) NSString *jyButton;
// 分项
@property (copy, nonatomic) NSString *fxButton;
// 施工
@property (copy, nonatomic) NSString *sgButton;
// 其他
@property (copy, nonatomic) NSString *otherButton;

// 选择监理View
@property (strong, nonatomic) TPKeyboardAvoidingTableView *selectedJLView;
// 监理cell
@property (strong, nonatomic) DefaineCell *JLCell;
// 监理数组
@property (strong, nonatomic) NSMutableArray *jlArr;

// 流程ID
@property (strong, nonatomic) NSString *processID;
// 记录当前被选择的监理的ID;
@property (strong, nonatomic) NSString *jlID;
// block参数
@property (strong, nonatomic) PositionBlockModel *blockModel;
// addressID
@property (copy, nonatomic) NSString *addressID;
@property (copy, nonatomic) NSString *positionwStr;

@end

@implementation SGFAddYSViewController

- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (NSMutableArray *)fileIdArr {
    if (_fileIdArr) {
        _fileIdArr = [NSMutableArray array];
    }
    return _fileIdArr;
}

// 选择监理view
- (TPKeyboardAvoidingTableView *)selectedJLView {
    if (!_selectedJLView) {
        _selectedJLView = [[TPKeyboardAvoidingTableView alloc] init];
        _selectedJLView.tag = 2000;
        _selectedJLView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _selectedJLView.backgroundColor = [UIColor lightGrayColor];
        _selectedJLView.dataSource = self;
        _selectedJLView.delegate = self;
    }
    return _selectedJLView;
}

// 监理cell
- (DefaineCell *)JLCell {
    if (!_JLCell) {
        _JLCell = [[DefaineCell alloc] init];
    }
    return _JLCell;
}

// 监理数据源
- (NSMutableArray *)jlArr {
    if (!_jlArr) {
        _jlArr = [[NSMutableArray alloc] init];
    }
    return _jlArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"添加验收";
    //附件模型
    _curTweet = [[Tweet alloc] init];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self loadViews];
    [self getDataSource];
    
    //编辑 加载新增数据数据
    if(self.superProcessId&&![self.superProcessId isEqualToString:@""])
    {
        self.blockModel=[[PositionBlockModel alloc]init];
        [self loadData];
        [self getAttachment];
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_ys" object:nil];
}


- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:4]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
}

-(void)loadViews{
    //添加右上方提交按钮
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
    [self.tableView registerClass:[selectBtnCell class] forCellReuseIdentifier:@"sCell"];
    [self.tableView registerClass:[PositionTableCell class] forCellReuseIdentifier:@"pCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ChooseMaterialCell" bundle:nil] forCellReuseIdentifier:@"chooseMaterial"];
    [self.tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
}


// 获取流程信息和流程记录信息
- (void)loadData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    //流程
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE ID = '%@' ORDER BY CREATE_TIME DESC limit 1", self.superProcessId];
    FMResultSet *result = [db executeQuery:sql];
    
    while ([result next]) {
        NSDictionary *dic=[result resultDictionary];
        self.processModel=[ProcessModel yy_modelWithDictionary:dic];
    }
    //流程记录
    NSString *sqlR = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC limit 1", self.superProcessId];
    FMResultSet *resultR = [db executeQuery:sqlR];
    while ([resultR next]) {
        NSDictionary *dic1=[resultR resultDictionary];
        self.processRecordModel =[ProcessRecordModel yy_modelWithDictionary:dic1];
        //项目地址id
        self.addressID=  self.processRecordModel.ADDRESS_ID;
        self.positionwStr=self.processRecordModel.ADDRES_INFO;
        self.content=self.processRecordModel.PROCESS_CONTENT;
        self.titleStr=self.processRecordModel.PROCESS_TITLE;
    }
    [db close];
    [self.tableView reloadData];
}

// 获取附件数据

- (void)getAttachment {
    //设置附件
    NSArray *imageArr=[LSUtility dictionaryWithJsonString:self.processRecordModel.FILEINFOS];
    
    // 查询附件表
    if(imageArr.count>0){
        for (NSDictionary *imageDic in imageArr) {
            NSString *fileId = imageDic[@"fileId"];
            // 记录当前图片附件的ID
            [self.fileIdArr addObject:fileId];
            NSString *fileName=[LSUtility queryAttachment:fileId][@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.selectedAssetURLs addObject:filePath];
        }
    }
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
}


// 获取监理数据
- (void)getDataSource {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *proID = DEF_PERSISTENT_GET_OBJECT(@"proid");
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PROJECT_USER WHERE PRO_ID = '%@' AND USER_TYPE = 'USER_03'", proID];
    FMResultSet *result = [db executeQuery:sql];
    // 模型数组
    NSMutableArray *modelArr = [NSMutableArray array];
    while ([result next]) {
        ProjectUserModel *model = [[ProjectUserModel alloc] init];
        model.ID = [result stringForColumn:@"ID"];
        model.PRO_ID = [result stringForColumn:@"PRO_ID"];
        model.UNIT_ID = [result stringForColumn:@"UNIT_ID"];
        model.USER_ID = [result stringForColumn:@"USER_ID"];
        model.USER_TYPE = [result stringForColumn:@"USER_TYPE"];
        model.PRO_USER_DESC = [result stringForColumn:@"PRO_USER_DESC"];
        model.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        model.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        model.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        model.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        model.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        model.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        [modelArr addObject:model];
        [self.jlArr addObject:model.USER_ID];
    }
    [db close];
}


#pragma mark--保存
- (void)clickSave {
    if (!self.blockModel.keyStr) {
        [LSUtility showToastWithMessage:@"请选择位置" inView:self.navigationController.view Andtime:1.];
        return;
    }
    if ([self.JLCell.text.text isEqual:@"请选择监理"]) {
        [LSUtility showToastWithMessage:@"请选择监理" inView:self.navigationController.view Andtime:1.];
        return;
        
    }
    if ([self.titleCell.textField.text isEqual:@""]) {
        [LSUtility showToastWithMessage:@"请输入标题" inView:self.navigationController.view Andtime:1.];
        return;
    }
    
    //编辑保存
    if(self.superProcessId)
    {
        [self updateProcess];
        [self updateProcessRecord];
    }
    //新增保存
    else{
        [self addFlowData];
        [self addFlowRecordData];
    }
    //上传附件
//    DataSynchronization  *sync=[[DataSynchronization alloc]init];
//    [sync uploadAttachsBackground];
    
    // 刷新列表页
    [[NSNotificationCenter defaultCenter] postNotificationName:@"editYS" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -编辑保存
//流程表
-(void)updateProcess{
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    NSString *jlStr = [[NSString alloc] init];
    
    if ([self.JLCell.text.text isEqual: @"请选择监理"]) {
        jlStr = @"";
    } else {
        jlStr = self.jlID;
    }
    // extendINFO
    NSDictionary *mapDic = @{};
    NSDictionary *extendDic = @{@"address":self.blockModel.keyStr, @"map":mapDic};
    NSData *extendData = [NSJSONSerialization dataWithJSONObject:extendDic options:0 error:nil];
    NSString *extendStr = [[NSString alloc] initWithData:extendData encoding:NSUTF8StringEncoding];
    // 生成流程ID
    self.processID = [NSUUID UUID].UUIDString;
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ADDRESS_ID":DEFISNUL(self.addressID),
                 @"ADDRES_INFO":DEFISNUL(self.positionwStr),
                 @"PROCESS_MASTERS":DEFISNUL(jlStr) ,
                 @"RECIFY_REVIEW_USERS":DEFISNUL(jlStr),
                 @"PROCESS_TITLE":self.titleStr,
                 @"MODIFY_TIME":[LSUtility nowTime],
                 @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"EXTEND_INFO":DEFISNUL(extendStr),
                 };
    [dbhelper DataBase:db updateTable:PROCESS setKeyValues:pragameDic whereCondition:@{@"ID":self.superProcessId}];
}

//流程记录表
-(void)updateProcessRecord{
    // 附件信息
    NSArray *fileinfosArr = [self insertAttachment:self.processRecordModel.ID];
    NSString *fileinfosStr;
    if (fileinfosArr) {
        fileinfosStr = [self toJSONData:fileinfosArr];
    }
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    // 施工方说明
    NSString *sgfState;
    if (self.ybButton && ![self.ybButton isEqualToString:@""]) {
        sgfState = self.ybButton;
    }
    if (self.jyButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.jyButton];
    } else if (self.jyButton && ![self.jyButton isEqualToString:@""]) {
        sgfState = self.jyButton;
    }
    if (self.fxButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.fxButton];
    } else if (self.fxButton && ![self.fxButton isEqualToString:@""]) {
        sgfState = self.fxButton;
    }
    if (self.sgButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.sgButton];
    } else if (self.sgButton && ![self.sgButton isEqualToString:@""]) {
        sgfState = self.sgButton;
    }
    if (self.otherButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.otherButton];
    } else if(self.otherButton && ![self.otherButton isEqualToString:@""]) {
        sgfState = self.otherButton;
    }
    
    NSString *jlStr = [[NSString alloc] init];
    if ([self.JLCell.text.text isEqual: @"请选择监理"]) {
        jlStr = @"";
    } else {
        jlStr = self.jlID;
    }
    
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ADDRESS_ID":DEFISNUL(self.addressID),
                 @"ADDRES_INFO":DEFISNUL(self.positionwStr),
                 @"RECORD_MASTER":DEFISNUL(jlStr),
                 @"PROCESS_TITLE":self.titleStr,
                 @"PROCESS_CONTENT":self.content,
                 @"PROCESS_DESC":DEFISNUL(sgfState),
                 @"REVIEW_USER":DEFISNUL(jlStr),
                 @"FILEINFOS":DEFISNUL(fileinfosStr),
                 @"MODIFY_USER_NAME":DEFISNUL(jlStr),
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":[LSUtility nowTime],
                 };
    [dbhelper DataBase:db updateTable:PROCESS_RECORD setKeyValues:pragameDic whereCondition:@{@"ID":self.processRecordModel.ID}];
}

#pragma  mrak--UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView.tag == 2000) {
        return 1;
    } else {
        return 5;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0 || section == 4){
        return 0.001;
    }else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 2000) {
        return self.jlArr.count;
        
    } else {
        if(section == 0){
            return 6;
        }else if (section == 1){
            return 2;
        } else {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 2000) {
        return 30;
    } else {
        long section=indexPath.section;
        long row=indexPath.row;
        if(section==0){
            if(row==0){
                return 40;
            }
            return 44;
        }else if(section==1){
            if(row==0){
                return 44;
                
            }else{
                return 100;
            }
        } else if(section == 3) {
            return 120;
            
        } else if(section == 4) {
            return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"附件"];
        } else {
            return 100;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if (tableView.tag == 2000) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.backgroundColor = [UIColor lightGrayColor];
        }
        cell.textLabel.text = [LSUtility getuserIdByUserName:self.jlArr[row]][@"REAL_NAME"];
        return cell;
    } else {
        if(section==0){
            if(row==0){
                
                TableTopStateCell *cell=[tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                
                if(self.processModel.CREATE_TIME ){
                    //截取时间
                    NSArray *timeArr=[self.processModel.CREATE_TIME componentsSeparatedByString:@" "];
                    NSString *time=[timeArr firstObject];
                    cell.title.text = [NSString stringWithFormat: @"%@验收录入", time];
                }else{
                    cell.title.text = [NSString stringWithFormat: @"%@验收录入", [LSUtility dateNow]];
                }
                return cell;
                
            }else if(row==1){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"项   目:";
                cell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
                return  cell;
                
            }else if(row==2){
                
                PositionTableCell *cell =[tableView dequeueReusableCellWithIdentifier:@"pCell" forIndexPath:indexPath];
                if(self.processModel){
                    NSDictionary *dic = [LSUtility dictionaryWithJsonString:self.processModel.EXTEND_INFO];
                    cell.btnStr  = dic[@"address"];
                    self.blockModel.keyStr=dic[@"address"];
                }else{
                    cell.btnStr = (self.blockModel.keyStr ? self.blockModel.keyStr : @"请选择位置");
                }
                
                cell.isEdit=YES;
                
                self.positionCell = cell;
                __weak PositionTableCell *weakCell = cell;
                cell.cliclWzBlock = ^{
                    
                    NSLog(@"位置");
                    OrientationViewController *location=[[OrientationViewController alloc]init];
                    location.flagStr = @"jilu";
                    
                    location.dataArr1 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                    location.dataArr2 = [NSMutableArray arrayWithArray:self.blockModel.dataArr2];
                    location.dataArr3 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                    location.dataArr4 = [NSMutableArray arrayWithArray:self.blockModel.dataArr1];
                    location.aID = self.blockModel.aID;
                    location.firstID = self.blockModel.firstID;
                    location.secondID = self.blockModel.secondID;
                    location.thirdID = self.blockModel.thirdID;
                    
                    location.keyStr = self.blockModel.keyStr;
                    location.number = self.blockModel.number;
                    location.addressArr = [NSMutableArray arrayWithArray:self.blockModel.addressArr];
                    location.position = self.blockModel.position;
//                    location.addressModel = self.blockModel.addressModel;
                    location.selectedX = self.blockModel.selectedX;
                    location.selectedY = self.blockModel.selectedY;
                    location.scale = self.blockModel.scale;
                    
                    if (location.number) {
                        location.hC = YES;
                    }
                    [self.navigationController pushViewController:location animated:YES];
//                     回传位置值
//                    location.returnPlaceInfoBlock = ^(PositionBlockModel *model){
//                        self.blockModel = model;
//                        weakCell.btnStr = model.keyStr;
//                        self.positionwStr = model.position;
//                        self.addressID = model.aID;
//                    };
                    
                    // 回传位置值
                    location.returnPlaceInfoBlock = ^(PositionBlockModel *model, AddressModel *addModel, NSString *addInfoStr){
                        self.blockModel = model;
                        weakCell.btnStr = model.keyStr;
                        self.positionwStr = model.position;
                        self.addressID = model.aID;
                    };
                };
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;
            }else if(row==4){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"报送人:";
                cell.text.text = DEF_PERSISTENT_GET_OBJECT(@"realname");
                return  cell;
            } else if (row==5){
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text=@"时   间:";
                if(self.processModel.CREATE_TIME ){
                    cell.text.text =self.processModel.CREATE_TIME;
                    self.nowTime=self.processModel.CREATE_TIME;
                }else{
                    self.nowTime = [LSUtility nowTime];
                    cell.text.text = self.nowTime;
                }
                
                return  cell;
            } else {
                DefaineCell *cell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                self.JLCell = cell;
                
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text=@"监   理:";
                
                //显示所选择监理
                if(self.processModel.PROCESS_MASTERS){
                    NSDictionary *dic=[LSUtility getuserIdByUserName:self.processModel.PROCESS_MASTERS];
                    cell.text.text=dic[@"REAL_NAME"];
                    self.jlID=self.processModel.PROCESS_MASTERS;
                }
                
                if ([self.JLCell.text.text isEqualToString:@""]) {
                    cell.text.text = @"请选择监理";
                } else {
                    cell.text.text = self.JLCell.text.text;
                }
                
                __weak typeof(cell) weakCell = cell;
                __weak typeof(self) weakSelf = self;
                
                [self.view addSubview:self.selectedJLView];
                [self.selectedJLView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(weakCell.mas_bottom);
                    make.left.mas_equalTo(weakCell.title.mas_right);
                    make.width.mas_equalTo(weakSelf.view.mas_width).multipliedBy(0.3);
                    make.height.mas_equalTo(self.jlArr.count * 31);
                }];
                self.selectedJLView.alpha = 0;
                return  cell;
            }
        } else if (section==1){
            if(row==0){
                QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
                self.titleCell = cell;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"标  题:";
                cell.textField.placeholder = @"请输入标题";
                //显示编辑
                if(self.processRecordModel.PROCESS_TITLE){
                    cell.textField.text=self.processRecordModel.PROCESS_TITLE;
                }
                cell.textValueChangedBlock = ^(NSString *tStr) {
                    self.titleStr = tStr;
                };
                
                return cell;
            }else{
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                self.contentCell = cell;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"内  容:";
                cell.text.placeholder = @"请输入内容";
                //显示编辑内容
                if(self.processRecordModel.PROCESS_CONTENT){
                    cell.text.text=self.processRecordModel.PROCESS_CONTENT;
                }
                
                cell.textValueChangedBlock = ^(NSString *cStr) {
                    self.content = cStr;
                };
                return cell;
            }
        } else if (section == 3) {
            // 附件类型
            ChooseMaterialCell *cell=[tableView dequeueReusableCellWithIdentifier:@"chooseMaterial" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.titleLabel.textColor = [TTTheme defaultManger].selectColor;
            
            //勾选上已经选择的项
            if (![self.processRecordModel.PROCESS_DESC isEqualToString:@""]&&self.processRecordModel) {
                NSArray *descArr = [self.processRecordModel.PROCESS_DESC componentsSeparatedByString:@"/"];
                
                if([descArr containsObject:@"隐蔽工程质量检验资料"]){
                    cell.ybgcBtn.selected=YES;
                    self.ybButton=@"隐蔽工程质量检验资料";
                }
                if ([descArr containsObject:@"检验批质量检验资料"]){
                    cell.jcplBtn.selected=YES;
                    self.jyButton=@"检验批质量检验资料";
                }
                if ([descArr containsObject:@"分项工程质量检验资料"]){
                    cell.fxgcBtn.selected=YES;
                    self.fxButton=@"分项工程质量检验资料";
                }
                if([descArr containsObject:@"施工实验室质量检验资料"]){
                    cell.sgBtn.selected=YES;
                    self.sgButton=@"施工实验室质量检验资料";
                }
                if([descArr containsObject:@"其他"]){
                    cell.qtBtn.selected=YES;
                    self.otherButton=@"其他";
                }
            }
            
            // 隐蔽
            cell.ybBlock = ^(NSString *ybStr) {
                self.ybButton = ybStr;
            };
            // 检验
            cell.jyBlock = ^(NSString *jyStr) {
                self.jyButton = jyStr;
            };
            // 分项
            cell.fxBlock = ^(NSString *fxStr) {
                self.fxButton = fxStr;
            };
            // 施工
            cell.sgBlock = ^(NSString *sgStr) {
                self.sgButton = sgStr;
            };
            // 其他
            cell.otherBlock = ^(NSString *otherStr) {
                self.otherButton = otherStr;
            };
            return  cell;
        } else if (section == 4) {
            WEAKSELF
            H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
            cell.isEdit = YES;
            [cell setTitle:@""];
            [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
            cell.curTweet = _curTweet;
            cell.addPicturesBlock = ^(){
                [weakSelf showActionForPhoto];
            };
            cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
                //移除图片
                [weakSelf.curTweet deleteATweetImage:toDelete];
                //移除数组
                [weakSelf.selectedAssetURLs removeObject:deUrl];
                
                [weakSelf refresh:nil];
            };
            
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            return cell;
            
        } else {
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.title.text = @"意  见:";
            cell.text.backgroundColor = [UIColor lightGrayColor];
            cell.isEdit = NO;
            return cell;
        }
    }
}

#pragma mark - 新增数据(流程表)
- (void)addFlowData {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    NSString *jlStr = [[NSString alloc] init];
    
    if ([self.JLCell.text.text isEqual: @"请选择监理"]) {
        jlStr = @"";
    } else {
        jlStr = self.jlID;
    }
    // extendINFO
    NSDictionary *mapDic = @{};
    NSDictionary *extendDic = @{@"address":self.blockModel.keyStr, @"map":mapDic};
    NSData *extendData = [NSJSONSerialization dataWithJSONObject:extendDic options:0 error:nil];
    NSString *extendStr = [[NSString alloc] initWithData:extendData encoding:NSUTF8StringEncoding];
    // 生成流程ID
    self.processID = [NSUUID UUID].UUIDString;
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":DEFISNUL(self.processID),
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"ADDRESS_ID":DEFISNUL(self.addressID),
                 @"ADDRES_INFO":DEFISNUL(self.positionwStr),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%d", PROCESS_TYPE_CHECK],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d", PROCESS_STAGE_START],
                 @"PROCESS_PUBLISHERS":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PROCESS_MASTERS":DEFISNUL(jlStr) ,
                 @"PROCESS_RECIFY_USERS":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PROCESS_RECIFY_UNITS":@"",
                 @"RECIFY_REVIEW_USERS":DEFISNUL(jlStr),
                 @"BEGIN_TIME":self.nowTime,
                 @"REQUIRED_END_TIME":@"",
                 @"END_TIME":@"",
                 @"PROCESS_TITLE":self.titleCell.textField.text,
                 @"CREATE_TIME":self.nowTime,
                 @"CREATE_USER_NAME":@"",
                 @"MODIFY_TIME":@"",
                 @"PROCESS_NUMBER":@"",
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"EXTEND_INFO":DEFISNUL(extendStr),
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS];
    if(isAdd){
        NSLog(@"验收新增成功");
    }else{
        NSLog(@"验收新增失败");
    }
}

#pragma mark - 新增数据(流程记录表)
- (void)addFlowRecordData {
    NSString *ID = [NSUUID UUID].UUIDString;
    // 附件信息
    NSArray *fileinfosArr = [self insertAttachment:ID];
    NSString *fileinfosStr;
    if (fileinfosArr) {
        fileinfosStr = [self toJSONData:fileinfosArr];
    }
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    // 施工方说明
    NSString *sgfState;
    if (self.ybButton && ![self.ybButton isEqualToString:@""]) {
        sgfState = self.ybButton;
    }
    if (self.jyButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.jyButton];
    } else if (self.jyButton && ![self.jyButton isEqualToString:@""]) {
        sgfState = self.jyButton;
    }
    if (self.fxButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.fxButton];
    } else if (self.fxButton && ![self.fxButton isEqualToString:@""]) {
        sgfState = self.fxButton;
    }
    if (self.sgButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.sgButton];
    } else if (self.sgButton && ![self.sgButton isEqualToString:@""]) {
        sgfState = self.sgButton;
    }
    if (self.otherButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.otherButton];
    } else if(self.otherButton && ![self.otherButton isEqualToString:@""]) {
        sgfState = self.otherButton;
    }
    
    NSString *jlStr = [[NSString alloc] init];
    if ([self.JLCell.text.text isEqual: @"请选择监理"]) {
        jlStr = @"";
    } else {
        jlStr = self.jlID;
    }
    
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":ID,
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"PROCESS_ID":DEFISNUL(self.processID),
                 @"WEATHER":@"",
                 @"ADDRESS_ID":DEFISNUL(self.addressID),
                 @"ADDRES_INFO":DEFISNUL(self.positionwStr),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%d", PROCESS_TYPE_CHECK],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d", PROCESS_STAGE_START],
                 @"RECORD_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%d", 0],
                 @"RECORD_MASTER":DEFISNUL(jlStr),
                 @"RECIFY_USER":@"",
                 @"RECIFY_UNIT":@"",
                 @"SEVERITY":@"",
                 @"END_TIME":@"",
                 @"SEND_TIME":DEFISNUL(self.nowTime),
                 @"SEND_TYPE":@"",
                 @"PROCESS_TITLE":self.titleCell.textField.text,
                 @"PROCESS_CONTENT":self.contentCell.text.text,
                 @"PROCESS_REQUIRED":@"",
                 @"PROCESS_DESC":DEFISNUL(sgfState),
                 @"SUBMITTORS":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"PUT_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"REVIEW_USER":DEFISNUL(jlStr),
                 @"REVIEW_OPINION":@"",
                 @"REVIEW_STATE":[NSString stringWithFormat:@"%d", REVIEW_STATE_UNPASS],
                 @"FILEINFOS":DEFISNUL(fileinfosStr),
                 @"EXTEND_INFO":@"",
                 @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"CREATE_TIME":DEFISNUL(self.nowTime),
                 @"MODIFY_USER_NAME":DEFISNUL(jlStr),
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_IP":@"",
                 @"MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_USER_NAME":@"",
                 @"LOCAL_MODIFY_TIME":@"",
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
        NSLog(@"验收记录添加成功");
    }else{
        NSLog(@"验收记录添加失败");
    }
}

#pragma mark - 先新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:@"PROCESS_03" andRecifyState:@"0"];
    }
    return rFileArr;
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}


/*
 *点击方法
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 2000) {
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.JLCell.text.text = [cell.textLabel.text mutableCopy];
        self.jlID = self.jlArr[indexPath.row];
        self.processModel.PROCESS_MASTERS= self.jlArr[indexPath.row];
        
        tableView.alpha = 0;
        
    } else {
        long section = indexPath.section;
        long row=indexPath.row;
        if (section == 0 && row == 3) {
            if (self.selectedJLView.alpha == 0) {
                [self.selectedJLView reloadData];
                self.selectedJLView.alpha = 1;
                DefaineCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                if(self.processModel.PROCESS_MASTERS){
                    NSDictionary *dic=[LSUtility getuserIdByUserName:self.processModel.PROCESS_MASTERS];
                    cell.text.text=dic[@"REAL_NAME"];
                }else{
                    cell.text.text = @"";
                }
            } else if (self.selectedJLView.alpha == 1) {
                self.selectedJLView.alpha = 0;
            }
        }
    }
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock=^(NSMutableArray *array){
            //            for (NSString *path in array) {
            //                //添加图片路径到已选数组
            //                [self.selectedAssetURLs addObject:path];
            //            }
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:4]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

@end
